package com.atwei.mango.system.securityHandler;

import com.atwei.mango.system.account.entity.Res;
import com.atwei.mango.system.account.service.ResService;
import com.atwei.mango.system.exception.ApiException;
import com.atwei.mango.system.exception.ResponseEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Classname UserPermissionEvaluator
 * @Description 校验权限
 * @Date 2022/6/9 16:11
 * @Author liuwei
 */
@Configuration
@Component
public class UserPermissionEvaluator implements PermissionEvaluator {

    @Autowired
    private ResService resService;


    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        SysAccount sysAccount = null;
        try{
            sysAccount = (SysAccount) authentication.getPrincipal();
        }catch (Exception e){
            throw new ApiException(ResponseEnum.DENIED);
        }
        List<Res> resByUserId = resService.getResByUserId(sysAccount.getId());
        if (null != resByUserId){
            // 判断是否拥有权限
            for (Res res : resByUserId) {
                if (permission.toString().equals(res.getPermission())){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
